package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.constant.Constants;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.MessagesApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.vo.ContactVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MessagesApi messagesApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 根据环信id 查询用户信息
     * @param huanxinId
     * @return
     */
    public UserInfoVo findUserByHuanxinUser(String huanxinId) {

        // 根据环信id查询 用户信息
        User user = userApi.findByHuanxinId(huanxinId);

        // 通过用户id查询用户详情
        UserInfo userInfo = userInfoApi.findById(user.getId());

        // 构造vo数据返回
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        userInfoVo.setAge(userInfo.getAge().toString());

        log.debug("*********userInfoVo********"+userInfoVo);
        return userInfoVo;
    }

    /**
     * 联系人添加
     */
    public void addContacts(Long userId) {

        Long loginUserId = UserHolder.getUserId(); // 当前用户id

        String username1 = Constants.HX_USER_PREFIX+userId.toString();
        String username2 = Constants.HX_USER_PREFIX+loginUserId.toString();

        // 在环信中将两个用户建立好友关系
        Boolean exits = huanXinTemplate.addContact(username1, username2);
        if(exits){
            throw new TanHuaException(ErrorResult.error());
        }

        // 往数据库中好友表中插入两条数据
        messagesApi.addContacts(userId,loginUserId);
    }

    /**
     * 分页查询联系人列表
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult<ContactVo> contactsList(Long page, Long pageSize, String keyword) {
        // 当前登录用户id
        Long userId = UserHolder.getUserId();
        // 分页查询好友信息
        PageResult<Friend> friendPageResult = friendApi.findPageByUserId(userId,page,pageSize);

        List<Friend> friendList = friendPageResult.getItems();
        List<ContactVo> contactVoList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(friendList)){
            List<Long> friendIds = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());

            UserInfo userInfoCondition = new UserInfo();
            userInfoCondition.setNickname(keyword);
            Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(friendIds, userInfoCondition);

            // 取出好友信息，转成vo
            for (Friend friend : friendList) {
                UserInfo userInfo = userInfoMap.get(friend.getFriendId());
                if(userInfo != null) {
                    ContactVo contactVo = ContactVo.init(userInfo);
                    contactVoList.add(contactVo);
                }
            }
        }

        
        return new PageResult<>(page,pageSize,friendPageResult.getCounts(),contactVoList);
    }
}
